<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
class Guser extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'index_admin/login' );
			exit ();
		}
	}
	/*
	 * 返回用户列表
	 */
	public function index() {
		$this->load->model ( 'user_model' );
		$this->load->model ( 'kickback_model' );
		$this->load->model ( 'order_model' );
		$users = $this->user_model->find_green_users ();
		foreach($users as $key=>$user){
			$kickbacks = $this->kickback_model->find_by_user ($user['id']);
			$users[$key]['amount']=0;
			$users[$key]['num'] = $this->order_model->find_orders_num ($user['id']);
			foreach($kickbacks as $kickback){
				if(!empty($kickback['newprice'])&&$kickback['purprice']>$kickback['newprice']){
					$users[$key]['amount']=1;
					break;
				}
			}
		}
		$data ['users']=$users;
		$data ['title'] = '用户管理 - 回扣管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'guser/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回添加蔬菜店用户页面
	 */
	public function add() {
		$data ['title'] = '添加特价用户 - 回扣管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'guser/add' );
		$this->load->view ( 'footer' );
	}
	 /*
	 * 设置蔬菜店用户
	 */
	public function save() {
		$adminid = $this->session->userdata ( 'id' );
		$userid = $this->input->post ( 'userid' );
		$price = $this->input->post ( 'price' );
		$user = array (
				'kickback' => 3
		);
		$this->load->model ( 'user_model' );
		$this->load->model ( 'product_model' );
		$this->load->model ( 'kickback_model' );
		if ($userid) {
			if($this->user_model->update( $userid, $user )){
	  			$products = $this->product_model->find_green_products ();
				foreach ( $products as $product ) {
					$kickback = array (
						'productid' => $product['id'],
						'userid' => $userid,
						'addprice' => $price,
						'admin' => $adminid,
						'date'=>date ( "Y-m-d H:i:s" )
					);
					$this->kickback_model->create ( $kickback );
				}
				return_json ( TRUE, '', '添加成功！' );
			}else{
				return_json ( FALSE, '', '添加失败！' );
			}
		}else{
			return_json ( FALSE, '', '用户ID不能为空！' );
		}
	}
}